<?php
/**
 * Created by 1971599474@qq.com
 * User: zhixuan
 * Date: 2019/12/17
 * Time: 22:20
 */

namespace app\admin\controller;

use app\common\controller\BaseController;
use app\common\utils\JsonService;
use think\captcha\facade\Captcha;
use think\facade\Session;
use think\facade\View;

class Login extends BaseController
{

    protected $error = '';

    public function index(){
        return View::fetch('index/login');
    }


    public function verify(){
        if($this->request->isAjax()){
            if($this->login() === TRUE){
                return JsonService::success('登录成功');
            }else{
                return JsonService::error($this->error);
            }
        }
    }

    //登录验证的方法
    public function login(){
        $account = input('post.account');
        $password = input('post.password');
        $cpcode = input('post.verifyCode');

        //先验证验证码
        if(empty($cpcode) || !captcha_check($cpcode)){
            $this->error = '验证码输入错误或没有填写';
            return FALSE;
        }
        //验证用户名与密码是否为空
        if(empty($account) || empty($password)){
            $this->error = '用户或密码不能为空';
            return FALSE;
        }
        //验证数据表里有没有此用户
        $user = \app\admin\model\Manage::getOne(['account'=>$account]);
        if($user){
            //判断用户启用状态
            //if($user->id == 1 || $user->is_use == 1){
            //验证密码
            if($user->password == md5(md5($password.$user->salt))){
                Session::set('adminUser',$user);
                Session::set('admin_id',$user->id);
                \app\admin\model\Manage::updateOne(['last_ip'=>$this->request->ip(),'last_time'=>time()],['id'=>$user->id]);
                return TRUE;
            }else{
                $this->error = '密码输入错误';
                return FALSE;
            }
            /*
            }else{
                $this->error = '此用户被禁用了';
                return FALSE;
            }
            */
        }else{
            $this->error = '此用户不存在';
            return FALSE;
        }
    }

    public function captcha()
    {
        $config = null;
        ob_clean();
        return Captcha::create($config);
    }

    /**
     * 退出登陆
     */
    public function logout()
    {
        Session::delete('adminUser');
        Session::delete('admin_id');
        $this->redirect(url('index')->build());
    }
}